//
//  ChatsViewController.m
//  EaseMob
//
//  Created by wwj on 16/5/26.
//  Copyright © 2016年 wfw. All rights reserved.
//

#import "ConversationsViewController.h"
#import "ContactsViewController.h"
#import "ConversationViewCell.h"
#import "ChatViewController.h"
#import "MeMConversation.h"
#import <Masonry.h>

//将数字转为
#define EMOJI_CODE_TO_SYMBOL(x) ((((0x808080F0 | (x & 0x3F000) >> 4) | (x & 0xFC0) << 10) | (x & 0x1C0000) << 18) | (x & 0x3F) << 24)

@interface ConversationsViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) NSMutableArray *conversations;
@property (weak, nonatomic) UITableView *tableView;
@end

@implementation ConversationsViewController
static NSString *const ID = @"ConversationViewCell";


- (NSMutableArray *)conversations{
    if (_conversations == nil) {
        _conversations = [NSMutableArray array];
    }
    return _conversations;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ConversationViewCell class]) bundle:nil] forCellReuseIdentifier:ID];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    _tableView = tableView;
    
    //获取历史会话记录
//    [self loadConversations];
    
    [self defaultEmoticons];
}

//测试数据
- (NSArray *)defaultEmoticons {
    NSMutableArray *array = [NSMutableArray new];
    for (int i=0x1F600; i<=0x1F64F; i++) {
        if (i < 0x1F641 || i > 0x1F644) {
            int sym = EMOJI_CODE_TO_SYMBOL(i);
            NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding];
            MyLog(@"%@", emoT);
            [array addObject:emoT];
        }
    }
    return array;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadConversations];
}

- (void)refrshAllMesssCount{
    NSInteger totalUnreadCount = 0;
    for (MeMConversation *model in self.conversations) {
        EMConversation *conversation = model.conversation;
        totalUnreadCount += [conversation unreadMessagesCount];
    }
    self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd", totalUnreadCount];
    [_tableView reloadData];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
    }];
}

#pragma 获取历史会话记录
- (void)loadConversations{
    //获取内存中所有会话
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* sorted = [conversations sortedArrayUsingComparator:
                       ^(EMConversation *obj1, EMConversation* obj2){
                           EMMessage *message1 = obj1.latestMessage;
                           EMMessage *message2 = obj2.latestMessage;
                           if(message1.timestamp > message2.timestamp) {
                               return(NSComparisonResult)NSOrderedAscending;
                           }else {
                               return(NSComparisonResult)NSOrderedDescending;
                           }
                       }];
    [self.conversations removeAllObjects];
    NSArray *newArray = [self getNewConversation:sorted];
    [_conversations addObjectsFromArray:newArray];
    [self refrshAllMesssCount];
}

- (NSArray *)getNewConversation:(NSArray *)dataArray{
    NSMutableArray *array = [NSMutableArray array];
    for (EMConversation *con in dataArray) {
        MeMConversation *econ = [[MeMConversation alloc] init];
        econ.conversation = con;
        [array addObject:econ];
    }
    return [array copy];
}



#pragma mark 未读消息数改变
- (void)refrshUnreadMessages{
    [self refrshAllMesssCount];
}

#pragma mark 会话列表发生变化
- (void)didUpdateConversationList:(NSArray *)aConversationList{
    self.conversations = [[self getNewConversation:aConversationList] mutableCopy];
    [self refrshAllMesssCount];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _conversations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ConversationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.model = _conversations[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatViewController *chatVC = [[ChatViewController alloc] init];
    MeMConversation *model = [_conversations objectAtIndex:indexPath.row];
    EMConversation *conversaion = model.conversation;
    chatVC.conversaionID = conversaion.conversationId;
    chatVC.chatType = conversaion.type;
    chatVC.titleStr = model.title;
    [self.navigationController pushViewController:chatVC animated:YES];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        MeMConversation *model = [_conversations objectAtIndex:indexPath.row];
        EMConversation *conversaion = model.conversation;
        __weak typeof(self) weakSelf = self;
        [[EMClient sharedClient].chatManager deleteConversation:conversaion.conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
            [weakSelf.conversations removeObjectAtIndex:indexPath.row];
            [weakSelf.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];
    }
}

#pragma mark 链接状态
-(void)setState:(EMConnectionState)state{
    if (state == EMConnectionConnected) {
        self.navigationItem.title = @"已连接";
    }else if (state == EMConnectionDisconnected){
        self.navigationItem.title = @"未连接";
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationItem.title = @"微信";
    });
}
@end
